#ifndef ________MOTOR_PWM_H________
#define ________MOTOR_PWM_H________

#include "stm32f1xx_hal.h"
#include "stdint.h"
#include "stdio.h"
#include "stdlib.h"
#include "stdbool.h"
#include "stdarg.h"
#include "string.h"
#include "math.h"

#include "motor_foc.h"

#ifdef __cplusplus
extern "C" {
#endif //__cplusplus

#define PWM_Freq_Target			16000		//PWM频率目标 Hz
#define PWM_Dead_Time			20			//PWM死区时间 us
#define PWM_Duty_Max            1000        //PWM占空比最大值(单位: 0.1%)
#define PWM_Duty_Default		0

typedef enum
{
	MOTOR_PWM_Chan_U_H,
	MOTOR_PWM_Chan_V_H,
	MOTOR_PWM_Chan_W_H,
	MOTOR_PWM_Chan_U_L,
	MOTOR_PWM_Chan_V_L,
	MOTOR_PWM_Chan_W_L,
	MOTOR_PWM_Chan_MAX
}MotorPWMChannelType_e;

typedef struct
{
	TIM_HandleTypeDef *htim;
	uint32_t channel;
	GPIO_HandleTypeDef *gpio;
	uint16_t pin;
	MotorPWMChannelType_e channel_type;
} MotorPWMChannelConfigType;


extern MotorPWMChannelConfigType g_pwm_channels[MOTOR_PWM_Chan_MAX];

// 初始化PWM模块
void motor_pwm_init(void);

// 配置PWM通道
void motor_pwm_set_channel(MotorPWMChannelConfigType pwm_channels[MOTOR_PWM_Chan_MAX], 
                          MotorPWMChannelType_e channel_type,
                          TIM_HandleTypeDef *htim,
                          uint32_t channel,
                          GPIO_TypeDef *port,
                          uint16_t pin);

// 设置PWM频率和死区时间
void motor_pwm_freq_set(MotorPWMChannelConfigType pwm_channels[MOTOR_PWM_Chan_MAX],
                       uint16_t freqBase, uint16_t dead_time);

void motor_pwm_set_duty(MotorPWMChannelConfigType pwm_channels[MOTOR_PWM_Chan_MAX],
                       MotorPWMChannelType_e channel_type, uint16_t duty);

// 设置三相PWM占空比（仅供高级用户使用，需确保不会导致直通）
void motor_pwm_set_duties_advanced(MotorPWMChannelConfigType pwm_channels[MOTOR_PWM_Chan_MAX],
                                  uint16_t duty_a, uint16_t duty_b, uint16_t duty_c);


// 启动PWM输出
void motor_pwm_start(void);

// 停止PWM输出
void motor_pwm_stop(void);


void motor_pwm_set_foc_outputs(MotorPWMChannelConfigType pwm_channels[MOTOR_PWM_Chan_MAX],
                              const FOCOutputs* foc_outputs);

#ifdef __cplusplus
}
#endif //__cplusplus

#endif // !________MOTOR_PWM_H________